package com.dave.admin.util;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Objects;

public abstract class UpdateWrapperUtil {


    public static Wrapper getUpdateWrapper(Object object) {
        return getUpdateWrapper(object, new String[]{});
    }

    public static Wrapper getUpdateWrapper(Object object, String... exclude) {
        return getUpdateWrapper(new UpdateWrapper(), object, exclude);
    }


    public static Wrapper getUpdateWrapper(UpdateWrapper updateWrapper, Object object, String... exclude) {
        Class clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();
        if (ArrayUtil.isNotEmpty(fields)) {
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = ReflectionUtils.getField(field, object);
                if (Objects.nonNull(value) && StringUtils.isNotBlank(value.toString()) && !ArrayUtil.contains(exclude, field.getName())) {
                    updateWrapper.eq(StrUtil.toUnderlineCase(field.getName()), value);
                }
            }
        }
        return updateWrapper;
    }
}
